package com.call.project.task;

import com.call.project.entity.SerialPort;
import com.call.project.jni.CInterface;
import com.call.project.utils.ConfigUtils;
import com.call.project.utils.OSinfo;
import com.call.project.utils.StatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 Created by IntelliJ IDEA.
 User: wk
 Date: 2017-03-22 下午2:38
 */
@Component
public class SerialPortTask {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private CInterface   cInterface;

    @Scheduled(fixedRate = 3000)
    public void checkPortStatus() {
        //logger.info("start checkPortStatus");
        if (OSinfo.isWindows()) {
            int status = cInterface.getStatus();
            if (status == StatusEnum.SUCCESS.getCode()) {
                logger.info("serialPort is success");
            } else {
                logger.warn("serialPort is error and try open");
                new Thread() {
                    @Override
                    public void run() {
                        startOpen();
                    }
                }.start();
            }
        }
    }

    public void startOpen() {
        logger.error("start startOpen");
        SerialPort serialPort = ConfigUtils.getSeriaPort();
        if (serialPort == null) {
            logger.error("serialPort not exists");
            return;
        }
        logger.info("serialPort data is {}", serialPort);
        boolean flag = false;
        for (int i = 1; i <= 6; i++) {
            flag = cInterface.initServer(i, serialPort.getRate(), serialPort.getPartity(),
                serialPort.getDatabits(), serialPort.getStopbits());
            if (flag)
                break;
        }
        logger.info("startOpen end {}", flag);

    }
}
